#!/usr/bin/env python3
"""
为管理员和用户生成随机任务的脚本
"""

import random
from datetime import datetime, timedelta
from database import get_db
from db_models import UserDB, TodoDB
from models import TodoStatus, TodoPriority, UserRole
from auth import init_default_users

def generate_sample_tasks():
    """为管理员和每个用户生成7个随机任务"""
    
    # 管理员任务池
    admin_tasks = [
        {
            "title": "制定团队季度规划",
            "description": "组织团队会议，讨论并制定下个季度的工作重点和目标",
            "priority": "high"
        },
        {
            "title": "审核项目预算申请",
            "description": "审查各部门提交的项目预算申请，评估投资回报率",
            "priority": "high"
        },
        {
            "title": "面试新员工候选人",
            "description": "安排并进行技术岗位的面试，评估候选人技能水平",
            "priority": "medium"
        },
        {
            "title": "优化团队工作流程",
            "description": "分析当前工作流程瓶颈，设计更高效的协作方式",
            "priority": "medium"
        },
        {
            "title": "准备月度工作汇报",
            "description": "整理团队月度工作成果，准备向上级汇报的材料",
            "priority": "medium"
        },
        {
            "title": "组织技术分享会",
            "description": "邀请技术专家举办内部分享会，提升团队技术水平",
            "priority": "low"
        },
        {
            "title": "更新团队管理制度",
            "description": "根据最新情况更新团队管理制度和工作规范",
            "priority": "low"
        }
    ]
    
    # 开发任务池
    dev_tasks = [
        {
            "title": "完成用户认证模块",
            "description": "实现JWT身份验证，包括登录、注册和权限验证功能",
            "priority": "high"
        },
        {
            "title": "优化数据库查询性能",
            "description": "分析慢查询日志，优化数据库索引和查询语句",
            "priority": "high"
        },
        {
            "title": "开发API接口文档",
            "description": "使用Swagger生成完整的API接口文档，方便前端调用",
            "priority": "medium"
        },
        {
            "title": "实现数据导出功能",
            "description": "开发支持Excel和CSV格式的数据导出功能",
            "priority": "medium"
        },
        {
            "title": "编写单元测试用例",
            "description": "为核心业务逻辑编写全面的单元测试，提高代码质量",
            "priority": "medium"
        },
        {
            "title": "修复页面响应式布局",
            "description": "解决移动端页面布局问题，确保在不同设备上正常显示",
            "priority": "low"
        },
        {
            "title": "集成第三方支付接口",
            "description": "接入支付宝和微信支付接口，完成支付流程开发",
            "priority": "low"
        },
        {
            "title": "实现消息推送功能",
            "description": "开发站内消息和邮件通知系统，提升用户体验",
            "priority": "medium"
        },
        {
            "title": "设计系统监控面板",
            "description": "搭建系统性能监控面板，实时监控服务器状态",
            "priority": "low"
        },
        {
            "title": "重构老旧代码模块",
            "description": "重构早期开发的代码模块，提高可维护性和性能",
            "priority": "medium"
        }
    ]
    
    # 学习任务池
    learning_tasks = [
        {
            "title": "学习React 18新特性",
            "description": "深入了解React 18的并发特性和Suspense机制",
            "priority": "medium"
        },
        {
            "title": "掌握TypeScript高级类型",
            "description": "学习泛型、条件类型、映射类型等TypeScript高级特性",
            "priority": "medium"
        },
        {
            "title": "研究微服务架构模式",
            "description": "学习微服务架构设计原则和最佳实践",
            "priority": "low"
        },
        {
            "title": "练习算法和数据结构",
            "description": "每日练习算法题，巩固计算机基础知识",
            "priority": "low"
        },
        {
            "title": "学习Docker容器技术",
            "description": "掌握Docker的使用方法和容器编排技术",
            "priority": "medium"
        },
        {
            "title": "阅读技术架构书籍",
            "description": "阅读《设计模式》《重构》等经典技术书籍",
            "priority": "low"
        },
        {
            "title": "参加技术会议",
            "description": "参加线上技术大会，了解行业最新发展趋势",
            "priority": "low"
        }
    ]
    
    # 生活任务池
    life_tasks = [
        {
            "title": "制定健身计划",
            "description": "设计包含有氧运动和力量训练的周运动计划",
            "priority": "medium"
        },
        {
            "title": "整理个人财务",
            "description": "梳理月度收支情况，制定储蓄和投资计划",
            "priority": "medium"
        },
        {
            "title": "学习烹饪新菜谱",
            "description": "尝试制作几道健康美味的新菜品",
            "priority": "low"
        },
        {
            "title": "规划周末旅行",
            "description": "研究周边景点，制定短途旅行计划",
            "priority": "low"
        },
        {
            "title": "整理房间物品",
            "description": "断舍离，整理房间物品，创造整洁的生活环境",
            "priority": "low"
        },
        {
            "title": "维护社交关系",
            "description": "主动联系老朋友，维护和发展人际关系",
            "priority": "medium"
        },
        {
            "title": "阅读个人成长书籍",
            "description": "阅读关于时间管理、沟通技巧的书籍",
            "priority": "low"
        }
    ]
    
    db = next(get_db())
    try:
        # 获取所有用户
        users = db.query(UserDB).all()
        print(f"找到 {len(users)} 个用户")
        
        for user in users:
            print(f"\n为用户 {user.username}（{user.role.value}）生成任务...")
            
            # 根据用户角色选择任务池
            if user.role == UserRole.ADMIN:
                task_pool = admin_tasks
                print("使用管理员任务池")
            else:
                # 为普通用户随机混合不同类型的任务
                all_user_tasks = dev_tasks + learning_tasks + life_tasks
                task_pool = random.sample(all_user_tasks, min(15, len(all_user_tasks)))
                print("使用混合任务池（开发+学习+生活）")
            
            # 随机选择7个任务
            selected_tasks = random.sample(task_pool, min(7, len(task_pool)))
            
            for i, task_data in enumerate(selected_tasks):
                # 随机状态分布：60%待处理，30%进行中，10%已完成
                status_weights = [
                    (TodoStatus.PENDING, 0.6),
                    (TodoStatus.IN_PROGRESS, 0.3),
                    (TodoStatus.COMPLETED, 0.1)
                ]
                status = random.choices(
                    [s[0] for s in status_weights],
                    weights=[s[1] for s in status_weights]
                )[0]
                
                # 获取用户当前最大的 order 值
                max_order = db.query(TodoDB.order).filter(
                    TodoDB.user_id == user.id
                ).order_by(TodoDB.order.desc()).first()
                next_order = (max_order[0] + 1) if max_order and max_order[0] is not None else i
                
                # 创建任务
                db_todo = TodoDB(
                    user_id=user.id,
                    title=task_data["title"],
                    description=task_data["description"],
                    status=status,
                    priority=TodoPriority(task_data["priority"]),
                    order=next_order,
                    assigned_by_admin=False  # 这些是用户自己的任务，不是管理员分配的
                )
                
                db.add(db_todo)
                print(f"  + {task_data['title']} [{status.value}] [{task_data['priority']}]")
            
        db.commit()
        print(f"\n✅ 成功为所有用户生成随机任务！")
        
        # 统计生成的任务
        total_tasks = db.query(TodoDB).count()
        print(f"📊 数据库中总任务数: {total_tasks}")
        
        for user in users:
            user_tasks = db.query(TodoDB).filter(TodoDB.user_id == user.id).count()
            print(f"   - {user.username}: {user_tasks} 个任务")
            
    except Exception as e:
        print(f"❌ 生成任务时出错: {e}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    print("🚀 开始为用户生成随机任务...")
    generate_sample_tasks()